package com.gf.controller.mnue;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gf.utils.Const;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;

/*
* 处理任意方式通过菜品的id来向购物车减少菜品的servlet
* */


@WebServlet(name = "deldish",urlPatterns = "/deldish")
public class DeldishServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        HttpSession session = request.getSession();
        JSONObject backjson = new JSONObject();
        HashMap<String ,Integer> shoppingcart =(HashMap<String ,Integer>) session.getAttribute("shoppingcart");
        if(shoppingcart==null)shoppingcart=new  HashMap<String ,Integer>();
        String dish_id = request.getParameter("dish_id");
        if (shoppingcart.get(dish_id)==1){
            shoppingcart.remove(dish_id);
        }else {
        shoppingcart.put(dish_id, shoppingcart.get(dish_id)-1);
        }
        session.setAttribute("shoppingcart",shoppingcart);
        PrintWriter out = response.getWriter();
        response.setStatus(200);
        backjson.put("status",200);
        backjson.put("message", Const.DELDISH_SUCESS);
        out.println(JSON.toJSON(backjson));
        out.flush();
        out.close();





    }
}
